<template>
    <!-- 人员薪酬管理 -->
    <div class="app-container">
        <el-form :model="ruleForm" ref="ruleForm" :inline="true" class="demo-ruleForm" v-show="showSearch">
            <el-form-item label="学院">
                <!-- <el-cascader v-model="ruleForm.xyDeptId" :options="deptOptions" clearable
                    :props="{ value: 'id', currentLabels: 'label', checkStrictly: true }" @change="handleChange"
                    @keyup.enter.native="search"></el-cascader> -->
                <el-select v-model="ruleForm.xyDeptId" placeholder="请选择" clearable class="elSelect"  style="width: 100%">
                    <el-option v-for="item in collegeData" :key="item.deptId" :label="item.deptName"
                    :value="item.deptId"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="专业">
                <el-select v-model="ruleForm.specialityId" clearable placeholder="请选择专业" @keyup.enter.native="search">
                    <el-option v-for="item in profession" :key="item.VALUE" :label="item.TITILE"
                        :value="item.VALUE"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="用工部门">
                <el-cascader v-model="ruleForm.deptId" :options="deptOptions" clearable
                    :props="{ value: 'id', currentLabels: 'label', checkStrictly: true }" @change="handleChanges"
                    @keyup.enter.native="search"></el-cascader>
            </el-form-item>
            <el-form-item label="薪酬状态">
                <el-select v-model="ruleForm.compStatus" clearable placeholder="请选择薪酬状态" @keyup.enter.native="search">
                    <el-option v-for="dict in dict.type.wsp_comp_status" :key="dict.value" :label="dict.label"
                        :value="dict.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="学生姓名">
                <el-input v-model="ruleForm.studentName" placeholder="请输入学生姓名"></el-input>
            </el-form-item>
         
            <el-form-item style="float:right;">
                <div>
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery" size="mini">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </div>
            </el-form-item>
        
        </el-form>
        <el-row :gutter="10" class="mb8" style="clear: both;">
            <el-col :span="1.5">
                <el-button type="primary" plain size="mini" v-hasPermi="['wsp:postempsalary:import']"
                    @click="upload.open = true">批量录入工时</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain size="mini" v-hasPermi="['wsp:postempsalary:settlement']" :disabled="multiple"
                    @click="handleSettlement">批量结算</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain size="mini" v-hasPermi="['wsp:postempsalary:settlementall']"
                    @click="handleSettlementAll">全部结算</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain size="mini" v-hasPermi="['wsp:postempsalary:view']"
                    @click="handleExport">下载录入工时模板</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button  size="mini" type="warning" plain icon="el-icon-download"
                    @click="handlePdf">导出word</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col> -->
            <right-toolbar :showSearch.sync="showSearch"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="用工部门" align="center" prop="wspPostEmpSalary.deptName" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="用工岗位" align="center" prop="wspPostEmpSalary.postName" :show-overflow-tooltip="true" />
            <el-table-column label="类型" align="center" prop="povertyType" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                        <dict-tag :options="dict.type.wsp_poverty_type"
                            :value="scope.row.povertyType"></dict-tag>
                </template>
            </el-table-column>
            <el-table-column label="开户银行" align="center" prop="bankName" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="银行卡号" align="center" prop="cardNumber" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="院系专业" align="center" prop="dm" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="班级" align="center" prop="className" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="学生姓名" align="center" prop="studentName" show-overflow-tooltip></el-table-column>
            <el-table-column label="注册号" align="center" prop="regCode" show-overflow-tooltip></el-table-column>
            <el-table-column label="联系电话" align="center" prop="mobile" show-overflow-tooltip></el-table-column>
            <el-table-column label="用工薪酬" align="center" prop="wspDeptPost.postComp" show-overflow-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.wspDeptPost.postComp }}元/小时
                </template>
            </el-table-column>
            <el-table-column label="预计时长" align="center" prop="wspDeptPost.workHours" show-overflow-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.wspDeptPost.workHours }}小时
                </template>
            </el-table-column>
            <el-table-column label="实际工时" align="center" prop="wspPostEmpSalary.totalHours" show-overflow-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.wspPostEmpSalary.totalHours ? scope.row.wspPostEmpSalary.totalHours : '未录入' }}
                    <span v-if="scope.row.wspPostEmpSalary.totalHours">小时</span>
                </template>
            </el-table-column>
            <el-table-column label="薪酬" align="center" prop="wspPostEmpSalary.comp" show-overflow-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.wspPostEmpSalary.comp ? scope.row.wspPostEmpSalary.comp : '未录入' }}
                    <span v-if="scope.row.wspPostEmpSalary.comp">元</span>
                </template>
            </el-table-column>
            <el-table-column label="薪酬状态" align="center" prop="wspPostEmpSalary.compStatus" show-overflow-tooltip>
                <template slot-scope="scope">
                    <div v-if="scope.row.wspPostEmpSalary.compStatus">
                        <dict-tag :options="dict.type.wsp_comp_status"
                            :value="scope.row.wspPostEmpSalary.compStatus"></dict-tag>
                    </div>
                    <div v-if="scope.row.wspPostEmpSalary.compStatus == null">
                        未录入
                    </div>

                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="handleEnter(scope.row)"
                        v-if="scope.row.wspPostEmpSalary.compStatus == null" v-hasPermi="['wsp:postempsalary:inputComp']">录入</el-button>
                    <el-button size="mini" type="text" @click="handleSettlement(scope.row)"
                        v-if="scope.row.wspPostEmpSalary.compStatus == 'Y' || scope.row.wspPostEmpSalary.compStatus == null ? false: true" v-hasPermi="['wsp:postempsalary:settlementSingle']" >结算</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="ruleForm.pageNum" :limit.sync="ruleForm.pageSize"
            @pagination="getList" />

        <!-- 录入弹窗 -->
        <el-dialog title="录入" :visible.sync="open" width="30%" append-to-body @close="cancel" destroy-on-close>
            <el-form ref="form" :model="form" :rules="rules" label-width="90px">
                <el-row>

                    <el-col :span="24">
                        <el-form-item label="输入工时" prop="totalHours">
                            <el-input v-model="form.totalHours" placeholder="请输入工时" maxlength="5">
                                <template slot="append">单位：小时</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm"> 录 入</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 批量录入工时 -->
        <el-dialog title="excel导入" :visible.sync="upload.open" width="400px" append-to-body>
            <div style="float: left;height: 30px;line-height: 30px;">上传文件：</div>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="onSuccess" :auto-upload="false">
                <div class="el-upload__text">
                    <i class="el-icon-upload"></i>
                    <em>点击上传</em>
                </div>
                <span style="height: 30px;line-height: 30px;margin-left: 10px;">仅支持 xls格式文件</span>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitUpload">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog title="上传结果" :visible.sync="uploadData" width="500px" append-to-body>
            <div>
                共录入数据{{studenData.totalSize}}条，上传成功{{studenData.successSize}}条，上传失败{{studenData.errorSize}}条，下载上传结果查看。
            </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importData">下载上传结果</el-button>
        <el-button @click="uploadData = false">取 消</el-button>
       
      </span>
    </el-dialog>
    <expro ref="addRefs"></expro>
    </div>
</template>
  
<script>
import {
    dutiesList,
} from "@/api/information/studentPosition";
import { deptTreeSelect } from "@/api/system/user";
import { getSpecialityByDeptId } from "@/api/information/unitMajor";
import { getStudentDpm } from "@/api/psychological/basic"
import { getToken } from "@/utils/auth";
import { postempsalaryList, inputComp,settlementall,updateSettlement } from '@/api/worStudy/personnelPay'
import PdfLoader from '@/utils/html2pdf'
import expro from '@/views/worStudy/personnelPay/expro copy'
import {
  collegeSelect
} from "@/api/information/studentInfor"
export default {
    dicts: [
        "wsp_comp_status",
        "wsp_poverty_type",
    ],
    components: {
        expro
    },
    data() {
        return {
            activeName: 'first',
            ruleForm: {
                pageNum: 1,
                pageSize: 10,
                specialityId: '',
                xyDeptId: '',
                compStatus: '',
                studentName: '',
                deptId: '',

                wspDeptPost: {},
                wspPostEmpSalary: {}
            },
            typeList: [],
            deptOptions: [],
            collegeData: [],
            profession: [],
            showSearch: true,
            activeTab: 0,
            multiple: true,
            uploadData: false,
            studenData: {},
            form: {
                studentName: undefined,
                dm: undefined

            },
            open: false,
            regCode: '', // 注册号 
            rules: {
                totalHours: [
                    { required: true, message: "请输入工时", trigger: "blur" },
                    { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
                ],
            },
            loading: false,
            total: 0,
            wpeIdList: [],
            importUrl: '',
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: true,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/wsp/postempsalary/importPostEmpSalary"
            },
        }
    },

    created() {
        this.department()
        this.getCollegeData()
        this.getList()
    },
    mounted() {
//   const exportId = document.getElementById('questionnaire')  // 需要导出部分页面的id名
//   this.pdfDownLoader = new PdfLoader(exportId, 'fileName', 'question-table')  // fileName -->导出文件名,  question-table -->防止被截断的class名
},
    methods: {

        handleChangeName(value) {
            console.log(value, '注册号')
            if (value === '') {
                return false;
            } else {
                getStudentDpm({ regCode: value }).then(res => {
                    this.form.studentName = res.data.STUDENTNAME
                    this.form.dm = res.data.DPM
                    this.form.studentId = res.data.STUDENT_ID

                })
            }
        },
        handleFileUploadProgress() { 
            this.upload.isUploading = true;
        },
        onSuccess(response) {
      if (response.code == 200) {
        this.$message.success("文件上传成功");
        this.studenData = response.data;
        this.importUrl = response.url
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.upload.open = false;
        this.uploadData = true;
        this.getList();
      } else {
        this.studenData = response.data;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.upload.open = false;
        this.uploadData = true;
        this.$message.error("文件上传失败");
        // this.getList();
      }
    },
    handlePdf() {
        // this.pdfDownLoader.outPutPdfFn('问卷分析')
        this.$refs.addRefs.open()
    },
        submitUpload() { 
              this.$refs.upload.submit();
        },
        /** 查询角色列表 */
        getList() {
            this.loading = true;
            postempsalaryList(this.ruleForm).then(response => {
                this.typeList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 获取部门信息
        async department() {
            await deptTreeSelect().then(res => {
                this.deptOptions = res.data;
            });
        },
        getCollegeData () {
            collegeSelect().then(res => {
                this.collegeData = res.data;
            });
        },
        // 下拉树选择
        handleChange(value) {
            if (typeof value == "object") {
                this.ruleForm.xyDeptId = value[value.length - 1];
                this.getSpeciality();
            } else if (typeof value == "number") {
                this.ruleForm.wspDeptPost.deptId = value;
                this.getSpeciality();
            } else if (value == undefined) {
                this.ruleForm.specialityId = "";
            }
            console.log(this.ruleForm.wspDeptPost.deptId, 'this.ruleForm.wspDeptPost.deptId')
        },
        // 下拉树选择
        handleChanges(value) {
            this.ruleForm.deptId = value[value.length - 1];
            console.log(this.ruleForm.deptId, 'this.ruleForm.wspPostEmpSalary.deptId')
        },
        getSpeciality() {
            if (this.ruleForm.xyDeptId) {
                getSpecialityByDeptId({ deptId: this.ruleForm.xyDeptId }).then(res => {
                    if (res.code == "200") {
                        this.profession = res.data;
                    } else {
                        console.log("123");
                        this.profession = [];
                    }
                });
            } else {
                this.profession = [];
            }
        },
        // 添加
        handleAdd() {
            this.open = true
        },
        // 录入
        handleEnter(row) {
            this.open = true
            this.form = row
        },
        handleQuery() {
            this.getList()
        },
        resetQuery() { 
            this.ruleForm = {}
            this.profession = []
            this.getList()
        },
        handleSelectionChange(selection) {
            this.wpeIdList = selection.map(e => e.wpeId)
            this.multiple = !selection.length;
        },
        cancel() {
            this.open = false;
        },
        // 结算
        handleSettlement(row) {
            const wpesId = row.wspPostEmpSalary.wpesId
            this.$confirm("确认结算，结算后该学生的工时将被锁定", "结算", {
                confirmButtonText: "结算",
                cancelButtonText: "取消",
            }).then(() => {
                updateSettlement(wpesId)
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("结算成功");
            })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消结算",
                    });
                });
        },
        // 全部结算
        handleSettlementAll() {
            settlementall().then(res=> {
                this.$modal.msgSuccess("全部结算成功");
            })
        },
        /** 录入按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    inputComp(this.form).then(response => {
                        if (response.code == 200) {
                            this.$modal.msgSuccess("录入成功");
                            this.open = false;
                            this.getList()
                           
                            this.form = {}
                        }

                    });
                }
            })
        },
        /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/wsp/postempsalary/importTemplate",
        {
          ...this.ruleForm
        },
        `人员薪酬${new Date().getTime()}.xlsx`
      );
    },
    importData() {
      let link = document.createElement("a"); 
      //创建一个a标签
      link.style.display = "none"; 
      //将a标签隐藏
      link.href = process.env.VUE_APP_BASE_API + this.importUrl; 
      //给a标签添加下载链接  "域名+接口"  safe是一个动态的域名  后面的接口替换成你自己的下载接口
      link.setAttribute("download", '下载上传结果'); 
      // 此处注意，要给a标签添加一个download属性，属性值就是文件名称 否则下载出来的文件是没有属性的，空白白
      document.body.appendChild(link);
      //将上面创建的a标签加入到body的尾部
      link.click(); 
      //执行a标签

    }
    }
};
</script>
  
<style lang="scss" scoped>
.tabs-nav-selected {
    color: #3192FC;
    border-bottom: 1px solid #3192FC;
    padding-bottom: 3px;
}

.tabs-header {
    cursor: pointer;
    line-height: 30px;
    height: 30px
}

.tabs-nav {
    line-height: 30px;
    margin-right: 5%;
}

.el-upload__text {
    color: #0077fa;
    border: 1px solid #0077fa;
    background-color: #dbdcdc;
    width: 100px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    float: left;
}
</style>